# -*- coding: utf-8 -*-
# Author: xiantingDeng
# File: request_util.py
# Time: 19:03

import requests
import sys
import os

sys.path.insert(1, os.path.dirname(os.path.dirname(os.path.abspath(""))))
from common.utils.read_util import OperationIni


class RestClient():
    def __init__(self, log, ip):
        self.__log = log
        self.__ip = OperationIni("setting.ini").get_ini_file_path_section_data("host").get(ip)

    def requests(self, url, method, data=None, json=None, timeout=None, **kwargs):
        try:
            headers = dict(**kwargs).get("headers")
            params = dict(**kwargs).get("params")
            files = dict(**kwargs).get("files")
            cookies = dict(**kwargs).get("cookies")

            response = requests.request(
                method=method,
                url=f"{self.__ip}{url}",
                data=data,
                json=json,
                params=params,
                headers=headers,
                files=files,
                cookies=cookies,
                timeout=timeout
            )

            time_total = response.elapsed.total_seconds()  # 获取响应时间
            status_code = response.status_code  # 获取响应码

            parameter = None

            if data is not "":
                parameter = data
            elif json is not "":
                parameter = json
            elif params is not "":
                parameter = params
            api_name = url.rsplit("/")[-3:]
            self.__log.info("-" * 100)
            self.__log.info('[ api name    ] : {}'.format("".join(api_name)))
            self.__log.info('[ request url ] : {}'.format(response.url))
            self.__log.info('[ headers     ] : {}'.format(headers))
            self.__log.info('[ cookies     ] : {}'.format(cookies))
            self.__log.info('[ method      ] : {}'.format(method.upper()))
            self.__log.info('[ parameter   ] : {}'.format(parameter))
            self.__log.info('[ status code ] : {}'.format(status_code))
            self.__log.info('[ time total  ] : {} s'.format(time_total))
            return response
        except Exception as e:
            self.__log.error("接口请求报错：{}".format(e))

